import CREATE_FILE_MAP from '@/data/create-file-map';

export function setNumToZh(number){
  if (number.length > 4 && number.length < 9) {
    return Math.round((parseInt(number) / 10000) * 100) / 100 + '万'
  }else if (number.length >= 9) {
    return Math.round((parseInt(number) / 100000000) * 100) / 100 + '亿'
  }else{
    return number
  }
}

// eslint-disable-next-line no-irregular-whitespace
export function getScrollTop() {　　
  var scrollTop = 0,
    bodyScrollTop = 0,
    documentScrollTop = 0;
  if (document.body) {
    bodyScrollTop = document.body.scrollTop;
  }
  if (document.documentElement) {
    documentScrollTop = document.documentElement.scrollTop;
  }
  scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
  return scrollTop;
}


export function getScrollHeight() {
  var scrollHeight = 0,
    bodyScrollHeight = 0,
    documentScrollHeight = 0;
  if (document.body) {
    bodyScrollHeight = document.body.scrollHeight;
  }
  if (document.documentElement) {
    documentScrollHeight = document.documentElement.scrollHeight;
  }
  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
  return scrollHeight;
}

export function getWindowHeight() {
  var windowHeight = 0;
  if (document.compatMode == "CSS1Compat") {
    windowHeight = document.documentElement.clientHeight;
  } else {
    windowHeight = document.body.clientHeight;
  }
  return windowHeight;
}

export function setToStore(key, value) {
  if (typeof localStorage === 'object') {
    try {
      if (typeof (value) == 'object' && !Array.isArray(value)) {
        value = JSON.stringify(value);
      }
        localStorage.setItem(key, value);
    } catch (e) {
      alert("请关闭无痕模式，否则部分功能将无法正常使用!");
    };
  };
}

export function removeFromStore(key) {
  if (typeof localStorage === 'object') {
    try {
      if (localStorage.getItem('userIdStore')) {
        let userId = localStorage.getItem('userIdStore');
        localStorage.removeItem(`${userId}/${key}`);
      } else {
        localStorage.removeItem(key);
      }
    } catch (e) {
      alert("请关闭无痕模式，否则部分功能将无法正常使用!");
    }
  }
}

export function removeCache() {
  if (typeof localStorage === 'object') {
    try {
      for (let key of CREATE_FILE_MAP) {
        localStorage.removeItem(key);
      }
    } catch (e) {
      alert("请关闭无痕模式，否则部分功能将无法正常使用!");
    }
  }
}

export function checkObjectField(target) {
  let msg = {};
  for (let p in target) {
    let val = target[p];
    if (Array.isArray(val)) {
      if (!val.length) {
        msg[p] = '数组为空'
      }
    }
  }
}

export function formatDate(date, con) {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  return `${year}${con}${month}${con}${day}`
}

export function getChoosedCode(list = {}, field) {
  let arr = [];
  for (let p in list) {
    if (list[p][field]) {
      arr.push(list[p].code + '');
    }
  }
  return arr;
}

export function handleColorData(colorOpt) {
  let ColorYes = [];
  let ColorMaybe = [];
  let ColorNever = [];
  for (let p in colorOpt) {
    let colorItem = colorOpt[p];
    if (colorItem.status == 1) {
      ColorYes.push(colorItem.code);
    }
    if (colorItem.status == 2) {
      ColorMaybe.push(colorItem.code);
    }
    if (colorItem.status == 3) {
      ColorNever.push(colorItem.code);
    }
  }
  return {
    ColorYes,
    ColorMaybe,
    ColorNever
  };
}

export function validatePhoneNumber(str) {
  let reg = /^1[3456789]\d{9}$/;
  return reg.test(str);
}

export function validatePassword(str) {
  let reg = /^.*(?=.{6,32})(?=.*\d)(?=.*[A-Za-z]).*$/;
  return reg.test(str)
}

// todo把常用的一些MAP映射放到这里
export const INDUSTRY_MAP = {

}
export function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

export function myBrowser() {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf("Opera") > -1;
  if (isOpera) {
    return "Opera"
  }; //判断是否Opera浏览器
  if (userAgent.indexOf("Firefox") > -1) {
    return "FF";
  } //判断是否Firefox浏览器
  if (userAgent.indexOf("Chrome") > -1) {
    return "Chrome";
  }
  if (userAgent.indexOf("Safari") > -1) {
    return "Safari";
  } //判断是否Safari浏览器
  if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
    return "IE";
  }; //判断是否IE浏览器

}

// eslint-disable-next-line no-unused-vars
export function initScale(params) {
  // window.addEventListener('pageshow', function (event) {
  //   alert(event.persisted);
  //   if (event.persisted) location.reload(); //如果检测到页面是从“往返缓存”中读取的，刷新页面
  // });
  // 为了检测微信返回，无法触发vuerouter的beforeeach
  // window.addEventListener("popstate", function (e) {
  //   console.log(location.href);
  // alert(document.referrer);
  // location.reload();
  // if (document.referrer)
  // document.location.href = document.location.href;
  // }, false);
  // var state = {
  //   title: "",
  //   url: ""
  // };
  // window.history.pushState(state, "", "");
  // 为了检测低版本safari的无痕模式
  if (typeof localStorage === 'object') {
    try {
      localStorage.setItem('localStorage', 1);
      localStorage.removeItem('localStorage');
    } catch (e) {
      alert("请关闭无痕模式，否则部分功能将无法正常使用!");
    };
  };
  //以下是调用上面的函数
  let mb = myBrowser();
  if ("IE" == mb) {}
  if ("FF" == mb) {}
  if ("Chrome" == mb) {}
  if ("Opera" == mb) {}
  if ("Safari" == mb) {
    document.documentElement.addEventListener('touchstart', function (event) {
      if (event.touches.length > 1) {
        event.preventDefault();
      }
    }, false);
    document.addEventListener('touchstart', function (event) {
      if (event.touches.length > 1) {
        event.preventDefault();
      }
    })
    var lastTouchEnd = 0;
    document.addEventListener('touchend', function (event) {
      var now = (new Date()).getTime();
      if (now - lastTouchEnd <= 300) {
        event.preventDefault();
      }
      lastTouchEnd = now;
    }, false)
    window.onload = function () {

    }
  }
}

export function accMul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) {}
  try {
    m += s2.split(".")[1].length;
  } catch (e) {}
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

export function checkObject(obj) {
  let flag = true;
  for (let p in obj) {
    if (!obj[p].trim()) {
      flag = false;
    }
  }
}

export function getDomain(params) {
  let protocal = window.location.protocol;
  let host = window.location.host;
  let result = `${protocal}//${host}`
  return result;
}

export function hackIOSInputFocus() {
  let height = document.documentElement.clientHeight;
  document.body.style.height = height + "px";
  document.body.style.overflow = "hidden";
  document.documentElement.style.height = height + "px";
  document.documentElement.style.overflow = "hidden";
}

export function removeIOSHack() {
  try {
    document.body.removeAttribute('style');
    document.documentElement.removeAttribute('style');
  } catch (error) {
    console.log(error)
  }

}
export function checkName(params) {
  let reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
  return reg.test(params);
}

export function getDataLength(fData) {
  var intLength = 0
  for (var i = 0; i < fData.length; i++) {
    if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
      intLength = intLength + 2
    else
      intLength = intLength + 1
  }
  return intLength
}

